<?php

declare(strict_types=1);

namespace App\AdminApi\Modular\Administer\Service;

use App\Common\Modular\Administer\Model\DepartmentModel;
use App\Common\Modular\Administer\Model\UserModel;
use App\Common\Modular\Administer\Serve\DepartmentServe;
use Core\Constants\Database;
use Core\Package\ElementPlus\FormCreate\Form;
use Core\Package\ElementPlus\FormCreate\FormItem;
use Hyperf\Database\Model\Relations\HasOne;
use Zms\Exception\AppException;
use Zms\Unit\Arr;

class DepartmentService extends DepartmentServe
{
    /**
     * 获取部门显示数据
     */
    public function getDepartmentData(array $where = []): array
    {
        $data = $this->getDepartmentAll($where);
        return Arr::getTree($data);
    }

    /**
     * 获取部门全部数据
     * @param array $where
     * @return array
     */
    private function getDepartmentAll(array $where = []): array
    {
        $all = $this->search()
            ->with(['manage' => function (HasOne $one) {
                $one->select(['id', 'nickname']);
            }])
            ->orderByRaw('sort DESC,id ASC')
            ->get()
            ->toArray();
        foreach ($all as &$item) {
            $item['id'] = (string)$item['id'];
            $item['label'] = $item['name'];
        }
        return $all;
    }

    /**
     * 获取部门完整关系链
     * @param int $id
     * @return array
     */
    public function getArchitectureIds(int $id): array
    {
        $all = $this->search()->orderByRaw('sort DESC,id ASC')->get()->toArray();
        $architecture = [];
        while ($id) {
            foreach ($all as $item) {
                if ($item['id'] === $id) {
                    $architecture[] = $id;
                    $id = $item['pid'];
                }
            }
            if (count($architecture) === 0) {
                break;
            }
        }
        return array_reverse($architecture);
    }


    /**
     * 获取部门数据字典
     */
    public function getTreeFormData(array $where = []): array
    {
        $data = $this->getDepartmentAll($where);
        $news = [];
        foreach ($data as $item) {
            $news[] = [
                'id' => (string)$item['id'],
                'pid' => (string)$item['pid'],
                'name' => $item['name'],
                'label' => $item['name'],
            ];
        }
        return Arr::getTree($news);
    }


    /**
     * 创建部门表单
     */
    public function createdForm($pid = 0): Form
    {
        $rule[] = FormItem::Hidden('pid', $pid ?: 0);
        $rule[] = FormItem::SearchPanel('manage_id', '部门主管', '/admin-api/filter-panel/depauth-user')
            ->columns([
                ['prop' => 'id', 'label' => 'ID'],
                ['prop' => 'nickname', 'label' => '名称'],
            ])
            ->labelKey('nickname')
            ->required('请选择部门主管');
        $rule[] = FormItem::Input('name', '部门名称')->placeholder('后台部门名称')->clearable(true)->maxlength(10)->required('请输入部门名称');
        $rule[] = FormItem::Number('sort', '部门排序')->placeholder('序号越大越靠前')->min(Database::INT_MIN)->max(Database::INT_MAX)->clearable(true);
        $rule[] = FormItem::Textarea('remark', '备注信息')->maxlength(100);
        return Form::create('添加部门')->setRules($rule)->setOptionFormInline(true);
    }


    /**
     * 编辑部门表单
     */
    public function updatedForm($id = 0): Form
    {
        /**
         * @var DepartmentModel $department
         */
        $department = $this->primaryByFirst($id);
        if ($department) {
            $rule[] = FormItem::Hidden('id', $id);
            $rule[] = FormItem::Input('name', '部门名称', $department->name)->placeholder('后台部门名称')->clearable(true)->maxlength(10)->required('请输入部门名称');
            $rule[] = FormItem::SearchPanel('manage_id', '部门主管', '/admin-api/filter-panel/depauth-user', $department->manage_id)
                ->columns([
                    ['prop' => 'id', 'label' => 'ID'],
                    ['prop' => 'nickname', 'label' => '名称'],
                    ['prop' => 'avatar', 'label' => '头像', 'type' => 'image'],
                ])
                ->simple(false)
                ->labelKey('nickname')
                ->selected(UserModel::class)
                ->required('请选择部门主管');
            $rule[] = FormItem::Number('sort', '部门排序', $department->sort)->placeholder('序号越大越靠前')->min(Database::INT_MIN)->max(Database::INT_MAX)->clearable(true);
            $rule[] = FormItem::Textarea('remark', '备注信息', $department->remark)->maxlength(100);
            return Form::create('编辑部门')->setRules($rule)->setOptionFormInline(true);
        }
        throw new AppException('部门已失效');
    }
}